package com.tonann.app.mqtt.mulitipleServer;

import com.alibaba.fastjson2.JSONObject;
import com.tonann.app.domain.AppSensor;
import com.tonann.app.mqtt.dao.DataBody;
import com.tonann.app.mqtt.dao.MQTTSensor;
import com.tonann.app.mqtt.dao.MessageBody;
import com.tonann.app.task.AnalyseTask;
import com.tonann.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 常规MQTT回调函数
 */
@Slf4j
public class MqttClientCallback { // implements MqttCallback {
//
//
////    private static RedisCache redisTemplate = SpringContextHolder.getBean(RedisCache.class);
////    private static SimpleProducer simpleProducer = SpringContextHolder.getBean(SimpleProducer.class);
////    private static WorkProducer workProducer = SpringContextHolder.getBean(WorkProducer.class);
//
//    private static AnalyseTask analyseTask = SpringContextHolder.getBean(AnalyseTask.class);
//
//    private int sameTimes = 5;
//
//    private BigDecimal rangeTop = BigDecimal.valueOf(0.2);
//
//    private BigDecimal rangeBottom = BigDecimal.valueOf(0.2);
//    /**
//     * 系统的mqtt客户端id
//     */
//    private String mqttClientId;
//
//    public MqttClientCallback(String mqttClientId) {
//        this.mqttClientId = mqttClientId;
//    }
//
//    /**
//     * MQTT 断开连接会执行此方法
//     */
//    @Override
//    public void connectionLost(Throwable throwable) {
//        log.info("断开了MQTT连接 ：{}", throwable.getMessage());
//        //log.error(throwable.getMessage(), throwable);
//    }
//
//
//    /**
//     * publish发布成功后会执行到这里
//     */
//    @Override
//    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//        log.info("发布消息成功");
//    }
//
//    /**
//     * subscribe订阅后得到的消息会执行到这里
//     */
//    @Override
//    public void messageArrived(String topic, MqttMessage message) throws Exception {
//        //  TODO    此处可以将订阅得到的消息进行业务处理、数据存储
////        System.out.println("收到来自 "+ mqttClientId + "====" + topic + " 的消息："+new String(message.getPayload()) );
////        MQTTMsg.getInstance().map.put("mqtt::" + mqttClientId + "::" + UUID.randomUUID().toString(),new String(message.getPayload()) );
////        redisTemplate.setCacheObject("mqtt:" + mqttClientId + ":" + UUID.randomUUID().toString(), new String(message.getPayload()));
////        log.info("收到来自 "+ mqttClientId + "====" + topic + " 的消息：{}", new String(message.getPayload()));
////            simpleProducer.sendMessage(new String(message.getPayload()));
////        if("TEST".equals(topic)){
////            //发送到rabbit消息队列
////            rabbitTemplate.convertAndSend("environmentDirectExchange", "environmentNilometer", message.getPayload());
////        }else {
////            log.info("测试主题进入" + topic +"主题判断方法=================");
////            //发送到rabbit消息队列
////            rabbitTemplate.convertAndSend("environmentDirectExchange", "environmentMeteor", message.getPayload());
////        }
//        String value = new String(message.getPayload());
//        MessageBody messageBody = JSONObject.parseObject(value, MessageBody.class);
//        try {
//            List<AppSensor> updateList = new ArrayList<>();
//            for (DataBody dataBody : messageBody.getValues()) {
////                 workProducer.sendMessage(JSON.toJSONString(dataBody));
////                new Thread(new Runnable() {
////                    @Override
////                    public void run() {
//                String tagId = dataBody.getId();
//                String v = dataBody.getValue();
//                if (StringUtils.isNotEmpty(v)) {
////                            long start = System.nanoTime();
//                    if (v.trim().equals("true")) {
//                        v = "1";
//                    } else if (v.trim().equals("false")) {
//                        v = "0";
//                    }
//                    AppSensor sensor = MQTTSensor.getInstance().map.get(tagId);
//                    if (sensor != null) {
//                        String oldValue = sensor.getValue();
//                        float result = new BigDecimal(v).setScale(2, RoundingMode.DOWN).floatValue();
//                        Long magnification = sensor.getMagnification() == null ? 1L : sensor.getMagnification();
//                        float r = result / magnification;
//                        BigDecimal bigDecimal = new BigDecimal(r + "");
//                        bigDecimal = bigDecimal.setScale(2, RoundingMode.DOWN);
//                        String updateValue = bigDecimal.floatValue() + "";
//                        sensor.setValue(updateValue);
//                        String userName = "modbus";
//                        sensor.setUpdateBy(userName);
//                        sensor.setUpdateTime(new Timestamp(new Date().getTime()));
//                        updateList.add(sensor);
//                        int valueCount = sensor.getValueCount();
//                        try {
//                            if (valueCount == 0 && !sensor.getAlarming()) {
//                                int res = analyseTask.faultAnalyse(sensor);
//                                if (res == 1) { // 如果触发告警
//                                    sensor.setValueCount(1);
//                                    sensor.setAlarming(true);
//                                } else {
//                                    sensor.setValueCount(0);
//                                }
//                            } else if (sensor.getAlarming()) {
//                                //如果相同的值出现规定次数以上，就重新赋值，可以进行告警分析
//                                if (valueCount >= sameTimes) {
//                                    sensor.setValueCount(0);
//                                    sensor.setAlarming(false);
//                                } else {
//                                    if (oldValue != null && !oldValue.isEmpty()) {
//                                        BigDecimal oldValueBigDecimal = new BigDecimal(oldValue);
//                                        rangeTop = oldValueBigDecimal.add(rangeTop);
//                                        rangeBottom = oldValueBigDecimal.subtract(rangeBottom);
//                                        //比较新值是否在可以波动的范围内
//                                        if (bigDecimal.compareTo(rangeTop) <= 0 && bigDecimal.compareTo(rangeBottom) >= 0) {
//                                            sensor.setValueCount(sensor.getValueCount() + 1);
//                                            sensor.setValue(oldValue);
//                                        }
//                                    } else {
//                                        sensor.setValueCount(sensor.getValueCount() + 1);
//                                    }
//                                }
//                            }
//                            MQTTSensor.getInstance().map.put(tagId, sensor);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
////                            long end = System.nanoTime();
////                            System.out.println("一个数据处理时间：" + (end - start));
//                }
//            }
//            analyseTask.analyseList(updateList);
////                }).start();
////            }
//        } catch (Exception e) {
//            e.printStackTrace();
////            System.out.println("Rabbit消息解释错误" + value);
//        }
//    }
}
